package com.gthncz.xxhelper.greendao;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

import com.gthncz.xxhelper.commons.Params;
import com.gthncz.xxhelper.commons.SQLFileHelper;

import org.greenrobot.greendao.database.Database;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;

/**
 * 客户端使用 Database 的帮助类
 * Created by GT on 2019/11/10.
 */

public class ClientDBHelper {
    private static final String TAG = ClientDBHelper.class.getSimpleName();

    private static ClientDBHelper mInstance;
    private static WeakReference<Context> weakContext;

    private DaoMaster daoMaster;
    private DaoSession daoSession;
    private DaoMaster.DevOpenHelper devOpenHelper;

    private ClientDBHelper(){
        // 执行一些初始化
        getDaoMaster();
        getDaoSession();
    }

    protected void finalize() throws java.lang.Throwable{
        super.finalize();
        closeConnection();
    }

    public static ClientDBHelper getInstance(Context context){
        if (mInstance == null){
            weakContext = new WeakReference<Context>(context);
            mInstance = new ClientDBHelper();
        }
        return mInstance;
    }

    public DaoMaster getDaoMaster(){
        if (daoMaster == null && weakContext.get() != null ){
            devOpenHelper = new DaoMaster.DevOpenHelper(weakContext.get(), Params.DB_NAME, null);
            daoMaster = new DaoMaster(devOpenHelper.getWritableDb());
        }
        return daoMaster;
    }

    public DaoSession getDaoSession(){
        if (daoSession == null){
            if (daoMaster == null){
                daoMaster = getDaoMaster();
            }
            daoSession = daoMaster.newSession();
        }
        return daoSession;
    }

    public DaoMaster.DevOpenHelper getDevOpenHelper(){
        if (devOpenHelper == null && weakContext.get() != null ){
            devOpenHelper = new DaoMaster.DevOpenHelper(weakContext.get(), Params.DB_NAME, null);
        }
        return devOpenHelper;
    }

    public void closeDevOpenHelper(){
        if (devOpenHelper != null){
            devOpenHelper.close();
            devOpenHelper = null;
        }
    }

    public void closeDaoSession(){
        if (daoSession != null){
            daoSession.clear();
            daoSession = null;
        }
    }

    public void closeConnection(){
        closeDevOpenHelper();
        closeDaoSession();
    }

    /**
     * 数据库是否已经被初始化
     * @return
     */
    public boolean isDBInited(){
        boolean inited = false;
        if (weakContext.get() != null){
            SharedPreferences sharedPreferences = weakContext.get().getSharedPreferences(Params.INI_NAME, Context.MODE_PRIVATE);
            inited = sharedPreferences.getBoolean("db_inited", false);
        }
        return inited;
    }

    /**
     * 第一次使用初始化数据
     * 重新初始化需要卸载 app 或者 删除数据表中的数据
     * 注：在子线程中执行。
     */
    public void init(){
        // 删除全部数据
        daoSession.getSubjectDao().deleteAll();
        // 从 sql 文件获取 sql 语句
        try {
            ArrayList<String> sqls = SQLFileHelper.getSqlsFromAssets(weakContext.get(), "tiku.sql");
            Database db = daoSession.getDatabase();
            Intent start = new Intent(Params.BROADCAST_INITING);
            start.putExtra("flag", 0xff);
            start.putExtra("size", sqls.size());
            weakContext.get().sendBroadcast(start);

            for(int i=0; i<sqls.size(); ++i){
                Log.i(TAG, String.format("db init, running %d: %s", i, sqls.get(i)));
                Intent intent = new Intent(Params.BROADCAST_INITING);
                intent.putExtra("flag", 0xf0);
                intent.putExtra("size", sqls.size());
                intent.putExtra("index", i);
                intent.putExtra("sql", sqls.get(i));
                weakContext.get().sendBroadcast(intent);
                db.execSQL(sqls.get(i));
            }

            // 写入配置文件
            SharedPreferences sharedPreferences = weakContext.get().getSharedPreferences(Params.INI_NAME, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putBoolean("db_inited", true);
            editor.commit(); // 记得提交

            Intent finish = new Intent(Params.BROADCAST_INITING);
            finish.putExtra("flag", 0x00);
            finish.putExtra("size", sqls.size());
            weakContext.get().sendBroadcast(finish);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
